package com.config.security;

import com.entity.sys.User;
import com.service.sys.UserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * Security配置类
 * @author clay
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private UserService userService;

    @Resource
    private RestAuthorizationEntryPoint restAuthorizationEntryPoint;

    @Resource
    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;

    @Resource
    private CustomerFilter customerFilter;
    @Resource
    private CustomerUrlDecisionManager customerUrlDecisionManager;


    //跳过security的链式拦截直接放行
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(
                "/login",
//                "/error", //加上这个
                "/logout",
                "/css/**",
                "/js/**",
                "/index.html",
                "/favicon.ico",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources/**",
                "/v2/api-docs/**",
                "/captcha",
                "/ws/**",
                "/swagger*//**",
                "/v2/api-docs",
                "/webjars*/**",
                "/img/imgUpload/**",
                "/emailFile/**",
                "/images/**",
                "/task/getCurrentTask/**"
        );
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //使用JWT, 不需要csrf
        http.
                cors().and() //开启cores试试
                .csrf()
                .disable()

                //基于token, 不需要session
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()

                .authorizeRequests()
                //配置允许登录, 即不需要认证即可授权的接口
                .antMatchers("/login", "/logout")
                //剩下的全部拦截
                .permitAll()
                .anyRequest()
                .authenticated()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    //动态权限配置
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O o) {
                        o.setAccessDecisionManager(customerUrlDecisionManager);
                        o.setSecurityMetadataSource(customerFilter);
                        return o;
                    }
                })
                .and()
                //关闭缓存
                .headers()
                .cacheControl();
        //添加jwt 登录授权过滤器 以及 验证码过滤器。
        http.addFilterBefore(jwtAuthTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        //不用自定义过滤器
//                .addFilterBefore(captchaFilter(), UsernamePasswordAuthenticationFilter.class);
        //添加自定义未授权和未登录结果返回
        http.exceptionHandling()
                .accessDeniedHandler(restfulAccessDeniedHandler)
                .authenticationEntryPoint(restAuthorizationEntryPoint);
    }

    /**
     * 重写userDetailsService, 这个只有一个方法loadUserByUsername, 登录实际会走这个方法
     * @return
     */
    @Override
    @Bean
    public UserDetailsService userDetailsService() {
        return username -> {
            User user = userService.getUserByUsername(username);
            if (Objects.nonNull(user)) {
                user.setRoles(userService.getRoles(user.getId()));
                return user;
            }
            throw new UsernameNotFoundException("用户名或密码不正确");
        };
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //将重写的userDetailsService防止在AuthenticationManager中, 以及配置了一个passwordEncoder
        //采用了BCryptPasswordEncoder
        auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
        super.configure(auth);
    }

    /**
     * 密码匹配
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public com.config.security.JwtAuthTokenFilter jwtAuthTokenFilter()
    {
        return new com.config.security.JwtAuthTokenFilter();
    }

//    @Bean
//    public CaptchaFilter captchaFilter()
//    {
//        return new CaptchaFilter();
//    }
}
